#ifndef CLIENTTHREAD_H
#define CLIENTTHREAD_H

#include <QThread>
#include <QWaitCondition>
#include <QJsonObject>
#include <QJsonDocument>
#include "ClientHandle.h"


class ClientThread : public QThread
{
    Q_OBJECT

signals:
    /*!
     * \brief receivedMessage is a signal emitted on readyRead.
     * \param msg is QString containing the contents of the socket.
     */
    void receivedMessage(const QByteArray &msg);

    /*!
     * \brief emits the clientClosed signal when the client disconnects.
     * \param id is an int which represents the socket descriptor.
     */
    void clientClosed(int id);

public:
    explicit ClientThread(qintptr _id, QObject *parent = 0);

    /*!
     * \brief run is the main method of this thread.
     */
    void run();

    /*!
     * \brief sendMessage appends a message to be sent to the queue.
     * \param msg is a QString which represents the message to append.
     */
    void sendMessage(const QByteArray &msg);

    /*!
     * \brief returns a pointer to an instance of client->
     */
    ClientHandle * getClient() const { return client; }

    /*!
     * \brief returns an int of the the socket descriptor.
     */
    int getThreadId() const { return socketId; }

    /*!
     * \brief writes a JSON message to the client's tcpSocket.
     * \param json is a QJsonObject which contains the details of the message to be written.
     */
    bool writeJSON(QJsonObject json);

public slots:
    /*!
     * \brief the readyRead slot is triggered when a message is received by the clientThread.
     */
    void readyRead();

    /*!
     * \brief the disconnected slot is triggered when the client disconnects from the server.
     */
    void disconnected();

private:
    ClientHandle *client;

    bool quit;

    QList<QByteArray> msgToWrite;

    qintptr socketId;
};

#endif // CLIENTTHREAD_H
